package tech.eyao.hs60x.serviceImpl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;

import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.PushPayload;
import io.jsonwebtoken.lang.Collections;
import tech.eyao.hs60x.cache.AccountCache;
import tech.eyao.hs60x.co.AccountCo;
import tech.eyao.hs60x.common.CommonConstants;
import tech.eyao.hs60x.common.ConstantsKey;
import tech.eyao.hs60x.common.ReturnCode;
import tech.eyao.hs60x.converts.AccountRelationConvert;
import tech.eyao.hs60x.dao.AccountDao;
import tech.eyao.hs60x.dao.AccountRelationDao;
import tech.eyao.hs60x.dao.ApprovalDao;
import tech.eyao.hs60x.dto.AddressBookDTO;
import tech.eyao.hs60x.dto.BaseResult;
import tech.eyao.hs60x.dto.BindDTO;
import tech.eyao.hs60x.dto.FriendDTO;
import tech.eyao.hs60x.dto.WatchFriendDTO;
import tech.eyao.hs60x.enums.AccountType;
import tech.eyao.hs60x.enums.ApprovalStatus;
import tech.eyao.hs60x.enums.Delete;
import tech.eyao.hs60x.enums.DeviceTag;
import tech.eyao.hs60x.enums.ExceptionCodeEnum;
import tech.eyao.hs60x.enums.RoleType;
import tech.eyao.hs60x.manager.IdGenService;
import tech.eyao.hs60x.model.domain.AccountDO;
import tech.eyao.hs60x.model.domain.AccountRelationDO;
import tech.eyao.hs60x.model.domain.ApprovalDO;
import tech.eyao.hs60x.service.AccountRelationService;
import tech.eyao.hs60x.utils.JPushUtils;
import tech.eyao.hs60x.vo.Command;

@Service
public class AccountRelationServiceImpl implements AccountRelationService {
    private static final Logger           logger       = LoggerFactory.getLogger(AccountRelationServiceImpl.class);
    @Autowired
    private AccountRelationDao            accountRelationDao;
    @Autowired
    private AccountDao                    accountDao;
    @Autowired
    private ApprovalDao                   approvalDao;
    @Autowired
    private AccountCache                  accountCache;
    @Autowired
    private IdGenService                  idGenService = null;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean insert(AccountRelationDO accountRelationDO) {
        return false;
    }

    @Override
    public AccountRelationDO getAccountAdminByWatchId(Long wacthAccountId) {
        return accountRelationDao.getAccountAdminByWatchId(wacthAccountId);
    }

    /**
     * 查询绑定手表列表
     */
    @Override
    public List<AccountRelationDO> getAccountRelationByAccountId(long userId) {
        return accountRelationDao.getAccountRelationByAccountId(userId);
    }

    @Override
    /**
     * 手表绑定
     */
    public BaseResult bindWatch(String relationName, Long userId, int bindType, String bindTips,
                                AccountDO deviceAccountDO) {
        logger.info("AccountRelationService bindWatch start>>>deviceAccountDO:{}",ToStringBuilder.reflectionToString(deviceAccountDO));
        BaseResult baseResult = new BaseResult();
        if (null == deviceAccountDO || StringUtils.isEmpty(deviceAccountDO.getDeviceId())) {
            return BaseResult.isFailure(ExceptionCodeEnum.ERROR_PARAMERROR.getCode(),
                    ExceptionCodeEnum.ERROR_PARAMERROR.getMessage());
        }
        try {
            long watchId = 0;
            //获取设备ID
            AccountDO accountDO = accountDao.getByDeviceId(deviceAccountDO.getDeviceId());
            if (null != accountDO) {
                watchId = accountDO.getId();
            } else {
                //创建账户
                accountDO = new AccountDO();
                BeanUtils.copyProperties(deviceAccountDO, accountDO);
                accountDO.setAccountType(AccountType.WATCH.getValue());
                accountDO.setDeviceTag(DeviceTag.WATCH.getValue());
                boolean addAccountStatus = accountDao.insert(accountDO);
                if (!addAccountStatus) {
                    return BaseResult.INSERT_EXCEPTION("新用户信息创建失败，请检查服务状态!");
                }
                watchId = accountDO.getId();
            }
            if (watchId <= 0 || userId <= 0) {
                return BaseResult.isFailure(ExceptionCodeEnum.ERROR_PARAMERROR.getCode(),
                        ExceptionCodeEnum.ERROR_PARAMERROR.getMessage());
            }
            if (watchId == userId.intValue()) {
                return BaseResult.isBussinessFail("不能绑定自己!");
            }

            // 已经绑定
            if (accountRelationDao.isBindWatch(userId, watchId)) {
                return BaseResult.isFailure(ExceptionCodeEnum.RECORD_EXISTS.getCode(),"当前用户已经绑定改设备,请确认手表联系人信息!");
            }

            AccountDO watchDo = accountDao.selectByPrimaryKey(watchId);
            if (null == watchDo || watchDo.getAccountType() != AccountType.WATCH.getValue()) {
                return BaseResult.isBussinessFail("绑定设备账户异常");
            }

            boolean result = Boolean.TRUE;
            AccountRelationDO accountRelationDO = accountRelationDao.getAccountAdminByWatchId(watchId);
            AccountDO currLoginAccount = accountDao.selectByPrimaryKey(userId);

            if (null == currLoginAccount || currLoginAccount.getAccountType() == AccountType.WATCH.getValue()) {
                return BaseResult.isBussinessFail("绑定失败，当前为手表用户！");
            }

            if (null == accountRelationDO) {
                AccountRelationDO newAccountRelationDO = new AccountRelationDO();
                newAccountRelationDO.setRoleCode(CommonConstants.ADMIN);
                baseResult.data = new BindDTO(CommonConstants.ADMIN);
                newAccountRelationDO.setRelationBusType(currLoginAccount.getAccountType());
                newAccountRelationDO.setRelationFunId(watchId);
                newAccountRelationDO.setRelationId(userId);
                newAccountRelationDO.setRelationName(relationName);
                result = accountRelationDao.insert(newAccountRelationDO);
                if (result) {
                    // 设置账户信息
                    if (null != deviceAccountDO.getBirthday())
                        accountDO.setBirthday(deviceAccountDO.getBirthday());
                    if (deviceAccountDO.getHeight() > 0)
                        accountDO.setHeight(deviceAccountDO.getHeight());
                    if (StringUtils.isNotEmpty(deviceAccountDO.getPhone()))
                        accountDO.setPhone(deviceAccountDO.getPhone());
                    if (StringUtils.isNotEmpty(deviceAccountDO.getNickName()))
                        accountDO.setNickName(deviceAccountDO.getNickName());
                    if (StringUtils.isNotEmpty(deviceAccountDO.getHeadUrl()))
                        accountDO.setHeadUrl(deviceAccountDO.getHeadUrl());
                    if (null != deviceAccountDO.getSex())
                        accountDO.setSex(deviceAccountDO.getSex());
                    if (deviceAccountDO.getWeight() > 0)
                        accountDO.setWeight(deviceAccountDO.getWeight());
                    accountDao.updateByPrimaryKey(accountDO);
                    // 管理用户手表关系
                    redisTemplate.opsForSet().add(ConstantsKey.getAdminKey(userId), String.valueOf(watchId));
                    redisTemplate.opsForValue().set(ConstantsKey.getWatchAdminKey(watchId), String.valueOf(userId));
                }
            } else {
                if (!approvalDao.isHas(watchId, userId, ApprovalStatus.NO.getValue())) {
                    // 进入申请
                    ApprovalDO approvalDO = new ApprovalDO();
                    approvalDO.setFriendId(userId);
                    approvalDO.setFriendPhone(currLoginAccount.getPhone());
                    approvalDO.setStatus(ApprovalStatus.NO.getValue());
                    approvalDO.setFriendNickName(relationName);
                    approvalDO.setOwnId(accountRelationDO.getRelationId());
                    approvalDO.setType(currLoginAccount.getAccountType());
                    approvalDO.setWatchId(watchId);
                    approvalDO.setRemark(bindTips);
                    result = approvalDao.insert(approvalDO);
                }
            }
            Map<String, Long> map = new HashMap<>();
            map.put("watchId", watchId);
            baseResult.data = map;
            baseResult.code = ReturnCode.C_SUCCESS_CODE;
            baseResult.message = ReturnCode.SUCCESS_CODE.getDesc();
        } catch (Exception e) {
            logger.error("[AccountRelationService bindWatch error.]", e);
            return BaseResult.isDeFaultFailure();
        }
        return baseResult;
    }

    @Override
    /**
     * 解绑逻辑
     */
    public BaseResult unbindWatch(Long watchId, long userId) {
        try {
            // 当前用户是否绑定手表
            AccountRelationDO accountRelationDO = accountRelationDao.getAccountRelation(userId, watchId);
            if (null == accountRelationDO) {
                return BaseResult.isBussinessFail("当前用户和设备无绑定关系");
            }
            // 校验手表信息
            AccountDO watchAccount = accountDao.getAccountById(watchId);
            logger.info("unbindWatch>>手表账户信息>>>watchAccount:{}", ToStringBuilder.reflectionToString(watchAccount));

            if (null != watchAccount && AccountType.PHONE.getValue() == watchAccount.getAccountType()) {
                return BaseResult.isBussinessFail("解绑目标非手表设备!");
            }
            //如果当前是管理员解绑，手机会先行判定是否管理员角色进行提示，服务端不再给予提示操作 直接解绑自身与所有与设备绑定关系(物理删除改为逻辑删除)
            if (CommonConstants.ADMIN.equalsIgnoreCase(accountRelationDO.getRoleCode())) {
                //解绑管理员关系,更新状态
                accountRelationDO.setIsDeleted(Delete.Y.getValue());
                boolean updateStatus = accountRelationDao.updateRelationByPrimaryKey(accountRelationDO);
                logger.info("解绑管理员关系,更新状态>>>updateStatus:{}", updateStatus);
                //逻辑删除所有与当前watch绑定者关系记录
                List<AccountRelationDO> relationList = accountRelationDao.getWatchRelationList(watchId);
                for (AccountRelationDO relationDO : relationList) {
                    relationDO.setIsDeleted(Delete.Y.getValue());
                    accountRelationDao.updateRelationByPrimaryKey(accountRelationDO);
                }
            }
            //删除redis 缓存的管理员KEY信息
            if (CommonConstants.ADMIN.equalsIgnoreCase(accountRelationDO.getRoleCode())) {
                redisTemplate.opsForSet().remove(ConstantsKey.getAdminKey(userId), String.valueOf(watchId));
                redisTemplate.delete(ConstantsKey.getWatchAdminKey(watchId));
                // 删除待审批信息
                approvalDao.deleteByOwnIdAndWatchId(userId, watchId);
                //发JPush 消息通知手表，进行初始化操作
                try {
                    // 是否为手表管理员
                    Command command = new Command(1031, "", System.currentTimeMillis(), idGenService.nextId(), watchId);
                    PushPayload payload = JPushUtils.sendMeassage(JSON.toJSONString(command), String.valueOf(watchId));
                    PushResult result = JPushUtils.getWatchInstance().sendPush(payload);
                    if (result.isResultOK()) {
                        logger.info("[CommandService sendCommand] result = {}", JSON.toJSON(result));
                    }
                } catch (Exception e) {
                    logger.error("[CommandService sendCommand]", e.getMessage());
                }
            }
        } catch (Exception e) {
            logger.error("[AccountRealationService unbindWatch error.]", e);
            return BaseResult.isDeFaultFailure();
        }
        return BaseResult.isSuccess();
    }

    @Override
    /**
     * 转移管理员
     */
    public BaseResult setWatchAdmin(long currentUserId, long currentWatchId, long targetAccountId, String nickName) {
        if (targetAccountId <= 0 || currentWatchId <= 0 ) {
            return BaseResult.isFailure(ExceptionCodeEnum.ERROR_PARAMERROR.getCode(),
                    ExceptionCodeEnum.ERROR_PARAMERROR.getMessage());
        }

        try {
            //获取手表账户信息
            AccountDO wAccountDO = accountDao.getAccountById(currentWatchId);
            logger.info("setWatchAdmin>>获取手表账户信息>>>wAccountDO:{}", ToStringBuilder.reflectionToString(wAccountDO));
            //获取转移目标账户信息
            AccountDO uAccountDO = accountDao.getAccountById(targetAccountId);
            logger.info("setWatchAdmin>>转移目标账户信息>>>uAccountDO:{}", ToStringBuilder.reflectionToString(uAccountDO));

            if (null == uAccountDO || null == wAccountDO) {
                return BaseResult.isBussinessFail("手表或转移目标账户不存在,请检查!");
            }
            if (wAccountDO.getAccountType() != AccountType.WATCH.getValue()
                    || uAccountDO.getAccountType() != AccountType.PHONE.getValue()) {
                return BaseResult.isBussinessFail("手表或转移目标账户设备类型不匹配!");
            }
            //根据当前手表设备获取唯一管理员绑定关系记录
            AccountRelationDO accountRelationDO = accountRelationDao.getAccountAdminByWatchId(currentWatchId);
            logger.info("setWatchAdmin>>管理员绑定关系记录>>>accountRelationDO:{}",
                    ToStringBuilder.reflectionToString(accountRelationDO));

            if (null == accountRelationDO) {
                return BaseResult.isBussinessFail("手表管理员绑定关系不存在，请核实watchId绑定关系记录!");
            }
            if (currentUserId != accountRelationDO.getRelationId().longValue()) {
                return BaseResult.isBussinessFail("当前转移账户非管理员校色，请核实当前用户!");
            }

            //更新当前用户为普通绑定用户角色
            accountRelationDO.setRoleCode(RoleType.NORMALUSER.getCode());
            boolean updateStatus = accountRelationDao.updateRelationByPrimaryKey(accountRelationDO);
            
            //查找转移目标用户的绑定关系并授权管理员角色
            AccountRelationDO targetAccountRelationDO = accountRelationDao.getAccountRelation(targetAccountId,
                    currentWatchId);
            if (null == targetAccountRelationDO) {
                return BaseResult.isFailure(ExceptionCodeEnum.RECORD_NOT_EXISTS.getCode(),
                        "转移目标账户与当前手表绑定关系不存在，请核实关系记录!");
            }
            if (updateStatus) {
                boolean targetUpdateStatus = accountRelationDao.updateRelationByPrimaryKey(targetAccountRelationDO);
                if (targetUpdateStatus) {
                    redisTemplate.delete(ConstantsKey.getAdminKey(currentUserId));
                    //opsForValue-->opsForSet
                    redisTemplate.opsForSet().add(ConstantsKey.getAdminKey(targetAccountId),String.valueOf(currentWatchId));
                    redisTemplate.opsForValue().set(ConstantsKey.getWatchAdminKey(currentWatchId),String.valueOf(targetAccountId));
                    // 删除待审批信息 初始化信息
                    //approvalDao.deleteByOwnIdAndWatchId(currentUserId, currentWatchId);
                }
                //查询原管理员下挂的审批记录，转移到目标用户上  getListByCondition
                List<ApprovalDO> approvalDOList = approvalDao.getListByCondition(currentUserId, currentWatchId);
                if (!Collections.isEmpty(approvalDOList)) {
                    //更改目标审批数据
                    for (ApprovalDO approvalDO : approvalDOList) {
                        approvalDO.setOwnId(targetAccountId);
                        approvalDao.updateByPrimaryKey(approvalDO);
                    }
                }

            }
        } catch (Exception e) {
            logger.error("[AccountRelationService setWatchAdmin error.]", e);
        }
        return BaseResult.isSuccess();
    }

    /**
     * 通讯录查询 返回当前手表绑定关系下的所有成员信息
     */
    public BaseResult findFriends(long userId, long watchId) {
        logger.info("通讯录查询>>>start userId:{},watchId:{}", userId, watchId);
        if (watchId <= 0) {
            return BaseResult.isFailure(ExceptionCodeEnum.ERROR_PARAMERROR.getCode(),
                    ExceptionCodeEnum.ERROR_PARAMERROR.getMessage());
        }

        try {
            AccountCo co = (AccountCo) accountCache.get(ConstantsKey.getAccountKey(userId));
            if (null != co && co.accountType == AccountType.PHONE.getValue()) {
                AccountRelationDO pAccountRelationDO = accountRelationDao.getAccountRelation(userId, watchId);
                if (null == pAccountRelationDO) {
                    return BaseResult.isBussinessFail("手机与当前设备绑定关系查无记录!");
                }
            }

            // convert
            List<AccountRelationDO> accountRelationDOs = accountRelationDao.getWatchRelationList(watchId);
            logger.info("手机通讯录查询结果>>>accountRelationDOs:{}", ToStringBuilder.reflectionToString(accountRelationDOs));

            List<AddressBookDTO> data = AccountRelationConvert.convert(accountRelationDOs);

            if (!CollectionUtils.isEmpty(data)) {
                data.forEach((a) -> {
                    AccountCo accountCo = (AccountCo) accountCache.get(ConstantsKey.getAccountKey(a.accountId));
                    a.phone = accountCo == null ? "" : accountCo.phone;
                    a.headImgUrl = accountCo.headUrl;
                    a.mail = accountCo.mail;
                });
            }
            logger.info("通讯录查询>>>end data:{}", ToStringBuilder.reflectionToString(data));
            return BaseResult.isSuccess(data);
        } catch (Exception e) {
            logger.error("[AccountRelationService findFriends error.]", e);
        }
        return BaseResult.isSuccess();
    }

    @Override
    public BaseResult findAllFriends(long userId, long watchId) {
        BaseResult baseResult = new BaseResult();
        if (watchId <= 0) {
            return BaseResult.isFailure(ExceptionCodeEnum.ERROR_PARAMERROR.getCode(),
                    ExceptionCodeEnum.ERROR_PARAMERROR.getMessage());

        }

        try {
            AccountCo co = (AccountCo) accountCache.get(ConstantsKey.getAccountKey(userId));

            if (null != co && co.accountType == AccountType.PHONE.getValue()) {
                AccountRelationDO pAccountRelationDO = accountRelationDao.getAccountRelation(userId, watchId);
                if (null == pAccountRelationDO) {
                    return BaseResult.isBussinessFail("无绑定关系");
                }
            }

            FriendDTO friendDTO = new FriendDTO();
            // convert
            List<AccountRelationDO> accountRelationDOs = accountRelationDao.getWatchRelationList(watchId);
            List<AddressBookDTO> addressBookDTOs = AccountRelationConvert.convert(accountRelationDOs);

            if (!CollectionUtils.isEmpty(addressBookDTOs)) {
                addressBookDTOs.forEach((a) -> {
                    AccountCo accountCo = (AccountCo) accountCache.get(ConstantsKey.getAccountKey(a.accountId));
                    a.phone = accountCo == null ? "" : accountCo.phone;
                    a.headImgUrl = accountCo.headUrl;
                    a.mail = accountCo.mail;
                });
            }
            friendDTO.addressBookDTOs = addressBookDTOs;
            List<WatchFriendDTO> watchFriendDTOs = AccountRelationConvert.convertWatchFriendDTO(accountRelationDOs);

            if (!CollectionUtils.isEmpty(addressBookDTOs)) {
                addressBookDTOs.forEach((a) -> {
                    AccountCo accountCo = (AccountCo) accountCache.get(ConstantsKey.getAccountKey(a.accountId));
                    a.phone = accountCo == null ? "" : accountCo.phone;
                    a.headImgUrl = accountCo.headUrl;
                    a.mail = accountCo.mail;
                });
            }

            friendDTO.watchFriendDTOs = watchFriendDTOs;
            baseResult = BaseResult.isSuccess(friendDTO);
        } catch (Exception e) {
            logger.error("[AccountRelationService findAllFriends error.]", e);
        }
        return baseResult;
    }

    /**
     * 校验当前账户是否管理员
     */
    @Override
    public Boolean checkUserIsAdmin(long userId) {
        if (0 == userId) {
            return false;
        }
        return accountRelationDao.isAdmin(userId);
    }

    @Override
    public BaseResult delete(long userId, long accountId, long watchId) {
        if (accountId < 0) {
            return BaseResult.isFailure(ExceptionCodeEnum.ERROR_PARAMERROR.getCode(),
                    ExceptionCodeEnum.ERROR_PARAMERROR.getMessage());
        }
        if (userId == accountId) {
            return BaseResult.isBussinessFail("自己不能删除自己");
        }
        try {
            // 获取watch的管理员
            AccountRelationDO admin = accountRelationDao.getAccountAdminByWatchId(watchId);

            if (null == admin || admin.getRelationId() != userId) {
                return BaseResult.isBussinessFail("当前登录用户非手表管理员");
            }

            AccountRelationDO accountRelationDO = accountRelationDao.getAccountRelation(accountId, watchId);
            if (null == accountRelationDO) {
                return BaseResult.isBussinessFail("删除的好友与手表无绑定关系");
            }
            boolean state = accountRelationDao.delete(accountRelationDO.getId());
            if (state)
                return BaseResult.isSuccess();
        } catch (Exception e) {
            logger.error("[AccountRelationService delete error.]", e);
        }
        return BaseResult.isDeFaultFailure();
    }
    
    /**
     * 手表联系人添加
     */
    public BaseResult addAddressBook(long userId, long watchId, String avatarUrl, String nickName, String phone) {
        try {
            // 绑定关系
            AccountRelationDO accountRelationDO = accountRelationDao.getAccountRelation(userId, watchId);
            // 当前手表管理员
            if (null != accountRelationDO && userId == Long.valueOf(redisTemplate.opsForValue().get(ConstantsKey.getWatchAdminKey(watchId)))) {
                AccountDO friendAccountDo = accountDao.getByPhone(phone);
                if (null == friendAccountDo || friendAccountDo.getAccountType() == AccountType.WATCH.getValue()) {
                    return BaseResult.isBussinessFail("好友账户异常");
                }
                // 绑定关系存在
                if (null != accountRelationDao.getAccountRelation(friendAccountDo.getId(), watchId)) {
                    return BaseResult.isBussinessFail("已经添加联系人" + StringUtils.defaultString(friendAccountDo.getNickName()));
                }
                friendAccountDo.setHeadUrl(avatarUrl);
                accountDao.updateByPrimaryKey(friendAccountDo);
                AccountRelationDO friendRelationDO = new AccountRelationDO();
                friendRelationDO.setRelationName(nickName);
                friendRelationDO.setRelationBusType(friendAccountDo.getAccountType());
                friendRelationDO.setRelationFunId(watchId);
                friendRelationDO.setRelationId(friendAccountDo.getId());
                accountRelationDao.insert(friendRelationDO);
            } else {
                return BaseResult.isBussinessFail("登录账号异常");
            }
        } catch (Exception e) {
            logger.error("[AccountRelationService addAddressBook error.]", e);
        }
        return BaseResult.isSuccess();
    }

    @Override
    public boolean isBindWatch(long userId, long watchId) {
        return accountRelationDao.isBindWatch(userId, watchId);
    }

    /**
     * 修改|更新手表端联系人
     */
    public BaseResult modifyAddressBook(long userId, long watchId, String historyPhone,
                                        String avatarUrl, String nickName,String modifyPhone) {
        logger.info(">>>>modifyAddressBook userId:{},watchId:{},historyPhone:{},avatarUrl:{},nickName:{},modifyPhone:{}",
                userId,watchId,historyPhone,avatarUrl,nickName,modifyPhone);
        AccountDO historyFriendAccountDo = null;
        try {
            // 绑定关系
            AccountRelationDO accountRelationDO = accountRelationDao.getAccountRelation(userId, watchId);
            // 当前手表管理员
            if (null != accountRelationDO && userId == Long.valueOf(redisTemplate.opsForValue().get(ConstantsKey.getWatchAdminKey(watchId)))) {
                //判定历史手机号是否存在账户信息，且与手表有绑定关系
                historyFriendAccountDo = accountDao.getByPhone(historyPhone);
                if (null == historyFriendAccountDo) {
                    return BaseResult.isFailure(ExceptionCodeEnum.RECORD_NOT_EXISTS.getCode(), "原手机:"+historyFriendAccountDo+"账户不存在!");
                }
                //校验历史账户与手表的绑定关系记录
                AccountRelationDO historyAccountRelationDO = accountRelationDao.getAccountRelation(historyFriendAccountDo.getId(), watchId);
                if (null == historyAccountRelationDO) {
                    return BaseResult.isFailure(ExceptionCodeEnum.RECORD_NOT_EXISTS.getCode(), "原手机:"+historyFriendAccountDo+"与手表无绑定关系!");
                }
                //校验新手机号的账户状态
                AccountDO checkExisttargetPhoneAccount = accountDao.getByPhone(modifyPhone);
                if(null!= checkExisttargetPhoneAccount) {
                    //校验新手机号是否在账户体系内，与当前设备是否存在绑定关系
                    AccountRelationDO currentRelationDO = accountRelationDao.getAccountRelation(checkExisttargetPhoneAccount.getId(), watchId);
                    if(null!= currentRelationDO) {
                        //不允许已经存在绑定关系的账户 进行手机号变更行为
                        return BaseResult.isFailure(ExceptionCodeEnum.INVALID_PARAMETER.getCode(), "不允许已经存在绑定关系的账户 进行手机号变更行为!");

                    }
                }
                //针对原有账户手机号进行替换变更，不做删除或新增操作
                if(StringUtils.isNotBlank(avatarUrl)) {
                    historyFriendAccountDo.setHeadUrl(avatarUrl);
                }
                if(StringUtils.isNotBlank(nickName)) {
                    historyFriendAccountDo.setNickName(nickName);
                }
                if(StringUtils.isNotBlank(modifyPhone)) {
                    historyFriendAccountDo.setPhone(modifyPhone);
                }
                accountDao.updateByPrimaryKey(historyFriendAccountDo);
                //更新关系表内存储的信息
                accountRelationDO.setRelationName(nickName);
                accountRelationDao.updateRelationByPrimaryKey(accountRelationDO);
            } else {
                return BaseResult.isBussinessFail("当前操作用户非管理员或系统异常!");
            }
        } catch (Exception e) {
            logger.error("[AccountRelationService delete error.]", e);
        }
        return BaseResult.isSuccess();
    }

}
